import java.util.Scanner;

public class Password{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        Password password = new Password();
        System.out.println("请输入要加密的密码");
        String input = in.nextLine();
        String encryptedPassword = password.encrypt(input);   //调用加密方法
        System.out.println("加密后的密码是"+encryptedPassword);
        System.out.println("请输入要解密的密码");
        String input2 = in.nextLine();
        String decryptedPassword = password.decrypt(input2);
        System.out.println("解密后的密码是"+decryptedPassword);
    }

    public static String encrypt(String password){   //加密方法

        if(password.length()>16){   //当密码长度超过16，抛出异常
            throw new IllegalArgumentException("密码长度不能超过16个字符");
        }

        StringBuilder encrypted = new StringBuilder();

        for(int i=0;i<password.length();i++){

            char c = password.charAt(i);   
            char encryptedChar = (char)(c+i+1+3);   ////将每个字符的ASCII码加上它在字符串中的位置（从位置1开始）和偏移值3
            encrypted.append(encryptedChar);   
  
        }

        char firstChar = encrypted.charAt(0);
        encrypted.setCharAt(0, encrypted.charAt(encrypted.length()-1));   //将字符串的首位和尾位进行调换
        encrypted.setCharAt(encrypted.length()-1, firstChar);

        char[] chars = encrypted.toString().toCharArray();   //将encrypted对象转换为字符串再转换为字符数组存储在char变量中

        for(int i = encrypted.length()/2;i>=0;i--){   //反转

            char temp = chars[i];
            chars[i] =chars[chars.length-1-i];
            chars[chars.length-1-i] = temp; 

        }

        return new String(chars);

    }

    public  static String decrypt(String input){
        StringBuilder decrypted = new StringBuilder();

        char[] dc = new char[input.length()];
        for(int i = dc.length-1;i>=0;i--){

            dc[input.length()-1-i]=input.charAt(i);


        }

        char firstChar = dc[dc.length-1];
        dc[dc.length-1]=dc[0];
        dc[0]=firstChar;

        for(int i = 0;i<dc.length;i++){
            int dcPw = (int)dc[i]-i-1-3;
            dc[i] = (char)dcPw;
        }

        return new String(dc);

      

    }
















    









}